<template>
  <div class="search_suggestion">
    <van-cell
      :key="item"
      @click="goSearch(item)"
      icon="search"
      v-for="item in suggestionData"
    >
      <div
        slot="title"
        v-html="highlight(item, keyword)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearch } from "../../../network/home";
import storage from "../../../utils/storage";

export default {
  name: "SearchSug",
  components: {},
  data() {
    return {
      suggestionData: [],
      keyword: ""
    };
  },
  created() {
    this.$bus.$on("sendSearchData", (res, val) => {
      this.suggestionData = res.options;
      this.keyword = val ? val : "";
    });
  },
  methods: {
    highlight(source, keyword) {
      // /searchContent/ 正则表达式中的一切内容都会当做字符串使用
      // 这里可以 new RegExp 方式根据字符串创建一个正则表达式
      // RegExp 是原生 JavaScript 的内置构造函数
      // 参数1：字符串，注意，这里不要加 //
      // 参数2：匹配模式，g 全局，i 忽略大小写
      const reg = new RegExp(keyword);
      return source.replace(reg, `<span style="color: red">${keyword}</span>`);
    },
    goSearch(val) {
      this.$emit("searchKeyWord", val);
      //本地存储历史记录
      let historyArr = storage.getItem("SEARCH_HISTORY") || [];
      if (historyArr.includes(val) !== true) {
        historyArr.push(val);
        storage.setItem("SEARCH_HISTORY", historyArr);
      }
    }
  }
};
</script>

<style scoped lang="stylus"></style>